package BESA.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class AddressHelper {

	public static List<String> getLocalAddressV4() {
		List<String> all = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> e = NetworkInterface
					.getNetworkInterfaces();
			while (e.hasMoreElements()) {
				NetworkInterface ni = e.nextElement();
				Enumeration<InetAddress> e2 = ni.getInetAddresses();
				while (e2.hasMoreElements()) {
					InetAddress ip = e2.nextElement();
					String ipS = ip.getHostAddress();
					if (!ipS.contains(":")) {
						all.add(ipS);
					}
				}
			}
		} catch (SocketException e1) {
			e1.printStackTrace();
		}
		Collections.reverse(all);
		return all;
	}

	public static boolean isValidIp(final String ip) {
		boolean correctFormat = ip
				.matches("^[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}$");

		if (correctFormat) {
			boolean validIp = true;

			String[] values = ip.split("\\.");
			for (int k = 0; k < values.length; ++k) {
				short v = Short.valueOf(values[k]).shortValue();
				if ((v < 0) || (v > 255)) {
					validIp = false;
					break;
				}
			}
			return validIp;
		}
		return false;
	}

}
